<template>
  <div>
    <div v-show="showList">
      <!-- 表单 -->
      <el-form size="small" :inline="true">
        <el-form-item label="模型标识">
          <el-input v-model="queryParams.modelKey" placeholder="请输入 模型标识" style="width:200px;"></el-input>
        </el-form-item>
        <el-form-item label="模型名称">
          <el-input v-model="queryParams.name" placeholder="请输入 模型名称" style="width:200px;"></el-input>
        </el-form-item>
        <el-button size="small" class="search_button" type="primary" icon="el-icon-search" @click="getModelList">查询</el-button>
        <el-button size="small" plain class="reset_button" type="info" icon="el-icon-refresh"
          @click="reset">重置</el-button>
      </el-form>

      <el-row>
        <el-button size="small" type="primary" icon="el-icon-folder-add" @click="addModel">新增</el-button>
        <el-button size="small" plain type="danger" icon="el-icon-delete" @click="removeModel">删除</el-button>
      </el-row>

      <!-- 表格 -->
      <el-table ref="multipleTable" style="width: 100%;margin-top:10px" border size="medium" :data="tableData"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column prop="" label="#" align="center" width="55"></el-table-column>
        <el-table-column prop="id" label="模型主键" align="center"></el-table-column>
        <el-table-column prop="modelKey" label="模型标识" align="center"></el-table-column>
        <el-table-column prop="name" label="模型名称" align="center"></el-table-column>
        <el-table-column prop="version" label="流程版本" align="center"></el-table-column>
        <el-table-column prop="created" label="创建时间" align="center"></el-table-column>
        <el-table-column prop="lastUpdated" label="更新时间" align="center"></el-table-column>
        <el-table-column prop="handle" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit-outline" plain
              @click="changeModel(scope.row.id)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-upload2" plain
              @click="deployModel(scope.row.id)">部署</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" plain
              @click="handleRemove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        :page-size="10" :page-sizes="[10, 20, 30, 40]" @current-change="handleCurrentChange"
        @size-change="handleSizeChange"></el-pagination>
    </div>


    <!-- <el-drawer title="流程配置" :visible.sync="workFlow" direction="btt" size="100%" :append-to-body="true"> -->
    <div id="flowBox" v-show="showList == false">
      <div id="toolbarBox">
        <bpmn-toolbar v-if="getEditorConfig.toolbar" />
        <el-button class="saveBtn" type="primary" @click="submit" icon="el-icon-edit-outline">保存流程</el-button>
        <i class="el-icon-close" @click="showList = true"></i>
      </div>
      <div class="main-content">
        <bpmn-designer :xml.sync="form.modelEditorXml" />
        <bpmn-panel v-if="getEditorConfig.penalMode === 'custom'" />
        <div v-else class="camunda-panel" id="camunda-panel"></div>
      </div>
      <!-- <bpmn-settings /> -->
      <bpmn-context-menu />
    </div>
    <!-- </el-drawer> -->






  </div>
</template>

<script>
import {
  getModelList, //获取列表
  submitModel, //新增/修改
  getDetail, //获取详情
  removeModel,//删除模型
  deployModel //部署模型
} from '_api/FlowManage/ModelManage/index.js'
import BpmnDesigner from "../../../packages/components/Designer";
import BpmnSettings from "../../../packages/components/Settings";
import { mapGetters } from "vuex";
import BpmnToolbar from "../../../packages/components/Toolbar";
import BpmnContextMenu from "../../../packages/components/ContextMenu/ContextMenu";
import BpmnPanel from "../../../packages/components/Panel";
import { defaultSettings } from "../../../packages/preset-configuration/editor.config";

export default {
  components: { BpmnPanel, BpmnContextMenu, BpmnToolbar, BpmnSettings, BpmnDesigner },
  props: {
    settings: {
      type: Object,
      default: () => defaultSettings
    }
  },
  data() {
    return {
      showList: true,
      // workFlow: false,
      // 查询参数
      queryParams: {
        current: 1,
        field: "",
        modelKey: "",
        name: "",
        order: "",
        pageSize: 10,
      },
      form: {
        description: "",
        id: "",
        modelKey: "",
        name: "",
        modelEditorXml: undefined
      },
      tableData: [],
      total: 0,
      //删除的id
      ids: [],
      editorSettings: this.settings
    };
  },
  computed: {
    ...mapGetters(["getEditorConfig"]),
    ...mapGetters(["getModeler"]),
  },
  methods: {
    reset() {
      this.queryParams = {
        current: 1,
        field: "",
        modelKey: "",
        name: "",
        order: "",
        pageSize: 10,
      }
      this.getModelList()
    },

    // 部署
    // todotodotodotodotodo
    // todotodotodotodotodo
    deployModel(e) {
      getDetail({ id: e }).then(res => {
        var deploy = {
          modelId: e,
          category: 0,
          tenantIds: res.data.data.tenantId
        }
        deployModel(deploy).then(res => {
          if (res.data.success == true) {
            this.$message.success(res.data.msg)
          }
        })
      })
    },
    // 新增
    addModel() {
      this.form = {
        description: "",
        id: "",
        modelKey: "",
        name: "",
        modelEditorXml: undefined
      },
        // this.workFlow = true
        this.showList = false
        this.$store.commit('OPEN_NAV')
    },
    //修改
    changeModel(e) {
      this.form.id = e
      getDetail({ id: e }).then(res => {
        console.log(res.data.data.modelEditorXml);
        // this.workFlow = true
        this.showList = false
        this.$store.commit('OPEN_NAV')
        this.form.modelEditorXml = res.data.data.modelEditorXml
      })
    },
    // 保存/编辑
    submit() {
      console.log(this.form.modelEditorXml);
      // console.log(this.$store.getters.getModeler._definitions.diagrams[0].plane.bpmnElement);
      var bpmn = this.$store.getters.getModeler._definitions.diagrams[0].plane.bpmnElement
      this.form.name = bpmn.name
      this.form.modelKey = bpmn.id
      // this.form.modelEditorXml = base64.encode(this.form.modelEditorXml, 'UTF-8')
      // this.form.modelEditorXml = base64.encode(encodeURIComponent(this.form.modelEditorXml), 'UTF-8')
      if (bpmn.documentation[0]) {
        this.form.description = bpmn.documentation[0].text
      }
      submitModel(this.form).then(res => {
        if (res.data.success == true) {
          this.$message.success(res.data.msg)
          // this.workFlow = false
          
          this.showList = true
          this.reset()
        } else {
          this.$message.info(res.data.msg)
        }
      })
    },
    // 多选
    handleSelectionChange(val) {
      console.log(val);
      val.forEach(item => {
        if (!this.ids.includes(item.id)) {
          this.ids.push(item.id)
        }
      })
      if (val.length == 0) {
        this.ids = []
      }
      // console.log(this.ids);
    },
    handleRemove(e) {
      this.ids = []
      this.ids.push(e)
      this.removeModel()
    },
    // 删除
    removeModel() {
      if (this.ids.length == 0) {
        this.$message.info("请先勾选!")
        return false
      }
      this.$confirm('此操作将删除该模型, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeModel({ ids: this.ids }).then(res => {
          if (res.data.success == true) {
            this.$message({
              message: '删除成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.ids = []
                this.reset()
              }
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleCurrentChange(e) {
      //当前页
      this.queryParams.current = e
      this.getModelList()
    },
    handleSizeChange(e) {
      this.queryParams.pageSize = e
      this.getModelList()
    },
    // 转换时间
    changeTime(time) {
      var date = new Date(time);
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
      return (Y + M + D + h + m + s);
    },
    // 列表
    getModelList() {
      getModelList(this.queryParams).then(res => {
        if (res.data.success == true) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.tableData.forEach(item => {
            item.created = this.changeTime(item.created)
            item.lastUpdated = this.changeTime(item.lastUpdated)
          })
        } else {
          this.tableData = res.data.data
          this.total = ""
          this.$message.info(res.data.message)
        }
      }).catch(error => {
        // if (error.response.status == 401) {
        //   this.$confirm('登录状态过期, 请重新登录!', '提示', {
        //     confirmButtonText: '确定',
        //     showCancelButton: false,
        //     type: 'warning'
        //   }).then(() => {
        //     this.$router.push('/login')
        //   }).catch(() => {
        //   })
        // }
      })
    }
  },
  created() {
    this.getModelList()
    this.editorSettings.paletteMode = "enhancement"
    this.$store.commit('setConfiguration', this.editorSettings)
  },
  mounted() {
    document.body.addEventListener("contextmenu", function (ev) {
      ev.preventDefault();
    });
  }
};
</script>

<style scoped>
.pagination {
  float: right;
  margin-top: 10px;
}

.el-form-item {
  font-weight: bold;
}

#toolbarBox {
  display: flex;
  /* align-items: center; */
  padding-bottom: 6px;
}

.saveBtn {
  height: 30px;
  margin-right: 8%;
}

.el-icon-close {
  font-size: 24px;
}
</style>